package com.xx.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xx.springboot.entity.CommonResult;
import com.xx.springboot.entity.ResponseBo;
import com.xx.springboot.entity.User;
import com.xx.springboot.mapper.UserMapper;
import com.xx.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoxiunique
 * @since 2018-08-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 用户登录
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public CommonResult loginUser(String userName, String password) {
        if (StringUtil.isBlank(userName) || StringUtil.isBlank(password))
            return new CommonResult(CommonResult.STATUS_ERROR, "请输入正确的用户名和密码");

        QueryWrapper<User> q = new QueryWrapper<>();
        q.eq("login_name", userName);
        q.eq("password", password);
        q.excludeColumns(User.class, "roleList");

        User loginUser = userMapper.selectOne(q);

        User qquser = userMapper.getUserByOpenId(userName, password);

        //TODO: 登录成功之后, 需要将用户信息填写到 缓存中
        if(loginUser != null){
            return new CommonResult(CommonResult.STATUS_SUCCESS, "登录成功", loginUser, null);
        }else {
            if(qquser != null)
                return new CommonResult(CommonResult.STATUS_SUCCESS, "登录成功", qquser, null);
            else
                return new CommonResult(CommonResult.STATUS_ERROR, "登录失败", loginUser, null);
        }
    }

    @Override
    public User getUserByOpenId(String userName, String openId) {
        return userMapper.getUserByOpenId(userName, openId);
    }

    @Override
    public User getUserListRole(Long userId) {
        return userMapper.getUserListRole(userId);
    }

    @Override
    public ResponseBo getUserList(Integer pageNo, Integer pageSize) {
        IPage<User> page = new Page<>();
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        IPage<User> list =  userMapper.getUserList(page);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list.getRecords());
        map.put("count", list.getTotal());
        return ResponseBo.ok(map);
    }
}
